//
//  EFengMineShareController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/3.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

//
//  EFengShareController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/2/29.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengMineShareController.h"
#import "UIBarButtonItem+category.h"
#import "EFengShareButton.h"
#import "EFengShareCell.h"
#import "EFengShare.h"
#import "EFengComposeController.h"
#import "CXmppRequestMgr.h"
#import "UIUtil.h"
#import "EFengShareFrame.h"
#import "EFengContent.h"
#import "CContactMgr.h"
#import "CFolderMgr.h"
#import "CContactModel.h"
#import "UIUtil.h"
#import "CShareMgr.h"
#import "CShareCommentMgr.h"
#import "MBProgressHUD+WZ.h"
#import "MJExtension.h"
#import "UIUtil.h"
#import "CAttentionMgr.h"
#import "CMineAttentionContact.h"
#import "EFengShareCommentToolBar.h"
#import "EFengShareEmotionView.h"
#import "MJRefresh.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "CShareCommentDelMgr.h"
#import "CShareDelMgr.h"
#import "EFengShareDel.h"
#import "EFengShareCommentDel.h"
#import "CFolderMgr.h"


@interface EFengMineShareController ()<UITableViewDataSource, UITableViewDelegate, EFengShareCellDelegate, EFengShareCommentToolBarDelegate>

WeakProperty UIView *topView;
WeakProperty EFengShareButton *selectedButton;

StrongProperty NSArray *dataArray;


StrongProperty UITableView *tableView;

StrongProperty CContactModel *curContact;
StrongProperty CContactMgr *conMgr;

StrongProperty CShareMgr *shareMgr;
StrongProperty CShareCommentMgr *commentMgr;
StrongProperty CShareCommentDelMgr *shareCommentDelMgr;
StrongProperty CShareDelMgr *shareDelMgr;
StrongProperty CAttentionMgr *attenMgr;

StrongProperty EFengContent *selectedComment;
StrongProperty EFengShare *selectedShare;
StrongProperty EFengShare *maxShare;
StrongProperty EFengShare *minShare;


@end



@implementation EFengMineShareController

#pragma mark 懒加载
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"我的分享"];
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-more" title:nil target:self sel:@selector(releaseShare) titleFont:Font18 titleColor:WhiteColor];
    
    self.shareMgr = [[CShareMgr alloc] init];
    self.commentMgr = [[CShareCommentMgr alloc] init];
    self.conMgr = [[CContactMgr alloc] init];
    self.attenMgr = [[CAttentionMgr alloc] init];
    self.shareCommentDelMgr = [[CShareCommentDelMgr alloc] init];
    self.shareDelMgr = [[CShareDelMgr alloc] init];
    
    self.curContact = [self.conMgr loadCurContact];
    
    
    self.tableView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    [self.view addSubview:self.tableView];
    
    
    //增加下拉刷新
    
    __block EFengMineShareController *weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    //增加上拉加载更多
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [weakSelf loadMoreData];
    }];
    [footer setTitle:@"加载更多..." forState:MJRefreshStateRefreshing];
    
    
    self.tableView.footer = footer;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
    [self.view addGestureRecognizer:tap];

}

- (void)releaseShare
{
    
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    nav.navigationBarHidden = NO;
    self.navigationController.navigationBarHidden = YES;
    
    EFengComposeController *compose = [[EFengComposeController alloc] init];
    [nav pushViewController:compose animated:YES];
}


- (void)loadData
{
    
    NSArray *array = [self.shareMgr getShareListWithSenderUserId:self.curContact.UserID];
    if (array.count > 0) {
        self.maxShare = array.firstObject;
        self.minShare = array.lastObject;
    }
    NSMutableArray *arrayM = [NSMutableArray array];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [array enumerateObjectsUsingBlock:^(EFengShare *obj, NSUInteger idx, BOOL *stop) {
            EFengShareFrame *shareF = [[EFengShareFrame alloc] init];
            obj.isFromMineShare = YES;
            obj.praiseCount = [NSString stringWithFormat:@"%zd",[self.commentMgr getSharePraiseAllReadCountWithShareId:obj.shareId]];
            obj.contentReply = [self.commentMgr getShareCommentWithShareId:obj.shareId];
            obj.isZan = [self.commentMgr isHasZanIdWithShareId:obj.shareId userId:self.curContact.UserID];
            shareF.share = obj;
            [arrayM addObject:shareF];
        }];
        self.dataArray = arrayM;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.header endRefreshing];
            [self.tableView reloadData];
        });
        
        
    });

}
- (void)loadMoreData
{
//    NSArray *array = [self.shareMgr getOlderShareWithMaxShareIndex:self.maxShare.ShareIndex releaseUserId:self.curContact.UserID];
//    if (array.count > 0) {
//        self.minShare = array.lastObject;
//        self.maxShare = array.firstObject;
//    }
//    NSMutableArray *arrayM = [NSMutableArray array];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [array enumerateObjectsUsingBlock:^(EFengShare *obj, NSUInteger idx, BOOL *stop) {
//            EFengShareFrame *shareF = [[EFengShareFrame alloc] init];
//            obj.isFromMineShare = YES;
//            obj.praiseCount = [NSString stringWithFormat:@"%zd",[self.commentMgr getSharePraiseAllReadCountWithShareId:obj.shareId]];
//            obj.contentReply = [self.commentMgr getShareCommentWithShareId:obj.shareId];
//            obj.isZan = [self.commentMgr isHasZanIdWithShareId:obj.shareId userId:self.curContact.UserID];
//            shareF.share = obj;
//            [arrayM addObject:shareF];
//        }];
//        self.dataArray = arrayM;
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView.footer endRefreshing];
//            [self.tableView reloadData];
//        });
//        
//        
//    });

}

- (void)loadNewData
{
//    NSArray *array = [self.shareMgr getNewerShareWithMinShareIndex:self.minShare.ShareIndex releaseUserId:self.curContact.UserID];
//    if (array.count > 0) {
//        self.maxShare = array.firstObject;
//        self.minShare = array.lastObject;
//    }
//    NSMutableArray *arrayM = [NSMutableArray array];
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [array enumerateObjectsUsingBlock:^(EFengShare *obj, NSUInteger idx, BOOL *stop) {
//            EFengShareFrame *shareF = [[EFengShareFrame alloc] init];
//            obj.isFromMineShare = YES;
//            obj.praiseCount = [NSString stringWithFormat:@"%zd",[self.commentMgr getSharePraiseAllReadCountWithShareId:obj.shareId]];
//            obj.contentReply = [self.commentMgr getShareCommentWithShareId:obj.shareId];
//            obj.isZan = [self.commentMgr isHasZanIdWithShareId:obj.shareId userId:self.curContact.UserID];
//            shareF.share = obj;
//            [arrayM addObject:shareF];
//        }];
//            
//        self.dataArray = arrayM;
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView.header endRefreshing];
//            [self.tableView reloadData];
//        });
//        
//        
//    });

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
    
    EFengShareCommentToolBar *tool = [EFengShareCommentToolBar defaultShareCommentToolBar];
    
    tool.eFengShareCommentToolBarDelegate = self;
    CGRect fr = tool.frame;
    fr.origin.y = HARDWARE_SCREEN_HEIGHT - 64.0f;
    tool.frame = fr;
    [self.view addSubview:tool];
    
    
    EFengShareEmotionView *emo = [EFengShareEmotionView defaultShareEmotionView];
    [self.view addSubview:emo];
    
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    EFengShareCommentToolBar *tool = [EFengShareCommentToolBar defaultShareCommentToolBar];
    tool.eFengShareCommentToolBarDelegate = nil;
    [tool removeFromSuperview];
    
    [[EFengShareEmotionView defaultShareEmotionView] removeFromSuperview];
    
}

#pragma mark tableView代理以及数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EFengShareFrame *share = self.dataArray[indexPath.row];
    return share.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EFengShareFrame *share = self.dataArray[indexPath.row];
    EFengShareCell *cell = [EFengShareCell eFengShaeCellWithTableView:tableView];
    cell.cellIndexPath = indexPath;
    cell.eFengShareCellDelegate = self;
    cell.shareFrame = share;
    return cell;
   
}
//bug 9130 fix by lixu
- (void)eFengShareCellDidClickHuiFuWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    self.selectedShare = share.share;
    self.selectedComment = nil;
    EFengShareCommentToolBar *toolBar = [EFengShareCommentToolBar defaultShareCommentToolBar];
    if ([toolBar.contentText isFirstResponder] || !toolBar.isEmotionShow) {
        [toolBar resetToolPositionToInitial];
        
    } else {
        [toolBar.contentText becomeFirstResponder];
        toolBar.contentText.text = @"";
        
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:inedexPath];
        CGPoint pt = self.tableView.contentOffset;
        CGFloat cellHeit = CGRectGetMaxY(cell.frame) + CGRectGetMaxY(self.topView.frame) - pt.y;
        if (cellHeit > toolBar.y) {
            
            
            pt.y = pt.y + cellHeit - toolBar.y;
            [self.tableView setContentOffset:pt animated:NO];
            
            
        } else {
            
            
        }
    }
    
}

- (void)eFengshareCommentsViewDidHuifuWithComment:(EFengContent *)comment share:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
    
//    self.selectedShare = share.share;
//    self.selectedComment = comment;
//    if ([comment.sendUserId isEqualToString:self.curContact.UserID]) {
//        
//        if ([[EFengShareCommentToolBar defaultShareCommentToolBar].contentText isFirstResponder] || ![EFengShareCommentToolBar defaultShareCommentToolBar].isEmotionShow) {
//            [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
//            self.tabBarController.tabBar.hidden = NO;
//        }
//        
//        
//        RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消" action:^{
//            
//        }];
//        
//        __block EFengMineShareController *block = self;
//        
//        RIButtonItem *selectItem = [RIButtonItem itemWithLabel:@"删除" action:^{
//            if ([comment.commentId isEqualToString:@""]) {
//                [block.commentMgr delShareCommentWithCommentIndex:comment.CommentIndex];
//            } else {
//                [block.commentMgr updateShareCommentIsUnNetCompletedWithComment:comment];
//                [[CXmppRequestMgr shareInstance] cancelPraiseShareWithCommentId:comment.commentId date:comment.date successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
//                    
//                    if ([responseObject[@"result"] isEqualToString:@"success"]) {
//                        
//                        [block.commentMgr delShareCommentWithCommentIndex:comment.CommentIndex];
//                    }
//                    
//                } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
//                    
//                }];
//            }
//            [self loadNewData];
//        }];
//        
//        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil cancelButtonItem:cancelItem destructiveButtonItem:nil otherButtonItems:selectItem, nil];
//        [actionSheet showInView:self.view];
//        
//        
//    } else {
//        if ([[EFengShareCommentToolBar defaultShareCommentToolBar].contentText isFirstResponder] || ![EFengShareCommentToolBar defaultShareCommentToolBar].isEmotionShow) {
//            [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
//            
//        } else {
//            [[EFengShareCommentToolBar defaultShareCommentToolBar].contentText becomeFirstResponder];
//            [[EFengShareCommentToolBar defaultShareCommentToolBar].contentText setText:@""];
//            [[EFengShareCommentToolBar defaultShareCommentToolBar].contentText setPlaceholder:[NSString stringWithFormat:@"回复%@",comment.sendUserName]];
//            
//            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:inedexPath];
//            CGPoint pt = self.tableView.contentOffset;
//            CGFloat cellHeit = CGRectGetMaxY(cell.frame) + CGRectGetMaxY(self.topView.frame) - pt.y;
//            if (cellHeit > [EFengShareCommentToolBar defaultShareCommentToolBar].y) {
//                pt.y = pt.y + cellHeit - [EFengShareCommentToolBar defaultShareCommentToolBar].y;
//                [self.tableView setContentOffset:pt animated:NO];
//            }
//        }
//    }
    
}
- (void)eFengShareCellDidClickShanChuWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
//    if ([share.share.shareId isEqualToString:@""]) {
//        
//        [self.shareMgr delShareWithShareIndex:share.share.ShareIndex];
//        
//    } else {
//        [self.shareMgr updateShareIsUnNetCompletedWithShare:share.share];
//        
//        [[CXmppRequestMgr shareInstance] delShareWithDate:share.share.date shareId:share.share.shareId successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
//            
//            if ([responseObject[@"result"] isEqualToString:@"success"]) {
//                [self.shareMgr delShareWithShareIndex:share.share.ShareIndex];
//            }
//            
//        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//        
//    }
//    [self loadNewData];
}
- (void)eFengShareCellDidClickZanWithShare:(EFengShareFrame *)share indexPath:(NSIndexPath *)inedexPath
{
//    if (share.share.isZan) {
//        EFengContent *comment = [self.commentMgr getZanIdWithShareId:share.share.shareId userId:self.curContact.UserID];
//        if ([comment.commentId isEqualToString:@""]) {
//            
//            [self.commentMgr delShareCommentWithCommentIndex:comment.CommentIndex];
//            
//        } else {
//            [self.commentMgr updateShareCommentIsUnNetCompletedWithComment:comment];
//            [[CXmppRequestMgr shareInstance] cancelPraiseShareWithCommentId:comment.commentId date:comment.date successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
//                
//                if ([responseObject[@"result"] isEqualToString:@"success"]) {
//                    
//                    [self.commentMgr delShareCommentWithCommentIndex:comment.CommentIndex];
//                }
//                
//            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
//                
//            }];
//            
//        }
//    } else {
//        EFengContent *comment = [[EFengContent alloc] init];
//        NSString *timeStamp = [UIUtil getCurrentTimeStamp];
//        NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,[timeStamp substringFromIndex:timeStamp.length - 6]];
//        comment.commentId = idStr;
//        comment.shareId = share.share.shareId;
//        comment.sendUserId = self.curContact.UserID;
//        comment.sendUserName = self.curContact.UserName;
//        comment.commentType = @"praise";
//        comment.isClick = YES;
//        comment.isRead = YES;
//        comment.date = [UIUtil getCurrentTimeStamp];
//        [self.commentMgr insertWithShareComment:comment];
//        [self loadNewData];
//        comment = [self.commentMgr getMaxShareComment];
//        [[CXmppRequestMgr shareInstance] praiseShareWithSendUserId:self.curContact.UserID commentId:idStr releaseUserId:share.share.releaseUserId contentId:share.share.shareId sendUserName:self.curContact.UserName successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
//            if ([responseObject[@"result"] isEqualToString:@"success"]) {
//                [self.commentMgr updateCommentWithCommentId:[NSString stringWithFormat:@"%@",responseObject[@"id"]]
//                                                            date:[NSString stringWithFormat:@"%@",responseObject[@"date"]]];
//            }
//            
//            
//        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//        
//    }
//    [self loadNewData];
}

- (void)sendMsg:(NSString *)txtMsg
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    self.tabBarController.tabBar.hidden = NO;
    if (M_ISSTRNULL(txtMsg)) {
        return;
    }
    NSString *type = nil;
    NSString *receiveUserId = nil;
    NSString *receiveUserName = nil;
    if (self.selectedComment) {
        type = @"reply";
        receiveUserId = self.selectedComment.sendUserId;
        receiveUserName = self.selectedComment.sendUserName;
    } else {
        type = @"comment";
    }
    
    EFengContent *content = [[EFengContent alloc] init];
    NSString *timeStamp = [UIUtil getCurrentTimeStamp];
    
    CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    NSString *idkey = serverSetting.yuLiuZiduan1;
    if (M_ISSTRNULL(idkey)) {
        idkey = @"111111";
    }
    NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,idkey];
    content.commentId = idStr;
    content.commentType = type;
    content.sendUserId = self.curContact.UserID;
    content.sendUserName = self.curContact.UserName;
    content.shareId = self.selectedShare.shareId;
    content.receiveUserId = receiveUserId;
    content.receiveUserName = receiveUserName;
    content.content = txtMsg;
    content.isClick = YES;
    content.isRead = YES;
    content.yuLiuZiduan2 = 1;
    content.date = [UIUtil getCurrentTimeStamp];
    [self.commentMgr insertWithShareComment:content];
    
    [[CXmppRequestMgr shareInstance] composeShareCommentWithShareId:self.selectedShare.shareId commentId:idStr releaseUserId:self.selectedShare.releaseUserId sendUserId:self.curContact.UserID sendUserName:self.curContact.UserName receiveUserId:M_STOREVALUE(receiveUserId) receiveUserName:M_STOREVALUE(receiveUserName) content:txtMsg type:type successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject[@"result"] isEqualToString:@"success"]) {
            [self.commentMgr updateCommentWithCommentId:[NSString stringWithFormat:@"%@",responseObject[@"id"]]
                                                        date:[NSString stringWithFormat:@"%@",responseObject[@"date"]]];
            [USER_DEFAULT setBool:YES forKey:@"sendOK"];
            [USER_DEFAULT synchronize];
        }

        
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    [self loadNewData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)didTap:(UITapGestureRecognizer *)tap
{
    [[EFengShareCommentToolBar defaultShareCommentToolBar] resetToolPositionToInitial];
    self.tabBarController.tabBar.hidden = NO;
}
- (void)emotionViewDidHidden
{
    [self.tabBarController.tabBar setHidden:NO];
}


@end
